﻿//Description:派工信息集成
//Copyright (c) : 通力凯顿（北京）系统集成有限公司
//Writer:Wangjh
//create Date:2018-04-18
//Rewriter:
//Rewrite Date:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using UFC.DBUtility;
using UFC.Common;
using System.Data.OracleClient;
using System.Configuration;
using System.Xml;

namespace SendToWCAPPDispatchInfo
{
    class SendDispatchInfo
    {
        private const string m_RecordType = "SendDispatchInfo";

        /// <summary>
        /// 结转数据到派工中间表
        /// </summary>
        public void RunDispatchTableSync()
        {

            System.Threading.Thread thInsertDispatch = new System.Threading.Thread(new System.Threading.ThreadStart(() =>
            {
                try
                {
                    InsertWCAPPTableSendDispatch();//插入批次派工信息

                }
                catch (Exception e)
                {
                    LogHelp.WriteError("插入批次派工信息" + e.Message, e);
                }
            }));
            thInsertDispatch.Start();

            System.Threading.Thread thUpdateDispatchOfModify = new System.Threading.Thread(new System.Threading.ThreadStart(() =>
            {
                try
                {
                    UpdateWCAPPDispatchOfModify();//更新派工修改结转信息
                }
                catch (Exception e)
                {
                    LogHelp.WriteError("更新派工修改结转信息" + e.Message, e);
                }
            }));
            thUpdateDispatchOfModify.Start();

            System.Threading.Thread thUpdateDispatchOfDelete = new System.Threading.Thread(new System.Threading.ThreadStart(() =>
            {
                try
                {
                    UpdateWCAPPDispatchOfDelete();//更新派工删除结转信息
                }
                catch (Exception e)
                {
                    LogHelp.WriteError("更新派工删除结转信息" + e.Message, e);
                }
            }));
            thUpdateDispatchOfDelete.Start();

            //add YangJiang 20180702
            System.Threading.Thread thInsertTDMDispatch = new System.Threading.Thread(new System.Threading.ThreadStart(() =>
            {
                try
                {
                    InsertTDMTableSendDispatch();//插入试车派工信息
                }
                catch (Exception e)
                {
                    LogHelp.WriteError("更新试车派工结转信息" + e.Message, e);
                }
            }));
            thInsertTDMDispatch.Start();

            //add YangJiang 20180709
            System.Threading.Thread thInsertZDSCDispatch = new System.Threading.Thread(new System.Threading.ThreadStart(() =>
            {
                try
                {
                    InsertZDSCTableSendDispatch();//插入作动筒信息
                }
                catch (Exception e)
                {
                    LogHelp.WriteError("更新作动筒结转信息" + e.Message, e);
                }
            }));
            thInsertZDSCDispatch.Start();


            do
            {
                System.Threading.Thread.Sleep(100);
            } while (thInsertDispatch.ThreadState != System.Threading.ThreadState.Stopped);//线程是否完成,插入批次派工信息
            do
            {
                System.Threading.Thread.Sleep(100);
            } while (thUpdateDispatchOfModify.ThreadState != System.Threading.ThreadState.Stopped);//线程是否完成,更新派工修改结转信息
            do
            {
                System.Threading.Thread.Sleep(100);
            } while (thUpdateDispatchOfDelete.ThreadState != System.Threading.ThreadState.Stopped);//线程是否完成,更新派工删除结转信息
            //add YangJiang 20180702
            do
            {
                System.Threading.Thread.Sleep(100);
            } while (thInsertTDMDispatch.ThreadState != System.Threading.ThreadState.Stopped);//线程是否完成,插入试车批次派工信息

            //add YangJiang 20180709
            do
            {
                System.Threading.Thread.Sleep(100);
            } while (thInsertZDSCDispatch.ThreadState != System.Threading.ThreadState.Stopped);//线程是否完成,插入作动筒信息
        }


        #region WCAPP数据结转
        /// <summary>
        /// 推送派工信息到WCAPP
        /// </summary>
        public void RunSendDispatchSyncToWCAPP()
        {
            string factoryCode = ConfigurationManager.AppSettings["WCAPP"].ToString();
            string FactoryID = GetFactoryIDByFactoryCode(factoryCode);
            DataTable dt = GetWCAPPWaitDispatchInfo(FactoryID);
            if (dt.Rows.Count == 0)
            {
                // LogHelp.WriteLog("没有可处理的派工信息记录");
                return;
            }
            foreach (DataRow dr in dt.Rows)
            {
                LogHelp.WriteLog("处理派工记录开始" + dr["taskNo"]);
                Dictionary<string, string> strList = new Dictionary<string, string>();
                strList.Add("TaskNo", dr["TASKNO"].ToString());//任务(派工)ID
                string strMsg = "";
                string type = "";
                if (dr["status"].ToString() == "0")//派工添加
                {
                    type = "派工添加";
                    AddDctionary(ref strList, dr);
                    string strXml = CreateWCAPPXML(strList, 0);
                    LogHelp.WriteLog("WCAPP推送添加派工的XML:" + strXml);
                    WCAPPService.WebService mm = new WCAPPService.WebService();
                    try
                    {
                        strMsg = mm.AddTask(strXml);
                    }
                    catch (Exception ex)
                    {
                        LogHelp.WriteLog(ex.Message);
                    }
                }
                else if (dr["status"].ToString() == "1")//派工删除
                {
                    type = "派工删除";
                    string strXml = CreateWCAPPXML(strList, 1);
                    LogHelp.WriteLog("WCAPP推送删除派工的XML:" + strXml);

                    WCAPPService.WebService mm = new WCAPPService.WebService();
                    try
                    {

                        strMsg = mm.DeleteTask(strXml);
                    }
                    catch (Exception ex)
                    {
                        LogHelp.WriteLog(ex.Message);
                    }
                }
                else if (dr["status"].ToString() == "2")//派工修改
                {
                    type = "派工修改";
                    AddDctionary(ref strList, dr);
                    string strXml = CreateWCAPPXML(strList, 2);
                    LogHelp.WriteLog("WCAPP推送修改派工的XML:" + strXml);
                    WCAPPService.WebService mm = new WCAPPService.WebService();
                    try
                    {
                        strMsg = mm.UpdateTask(strXml);

                    }
                    catch (Exception ex)
                    {
                        LogHelp.WriteLog(ex.Message);
                    }


                }
                LogHelp.WriteLog("WCAPP返回的XML:" + strMsg);
                if (GetRcvXML(strMsg))
                {
                    UpdateDispatchTable(dr["taskno"].ToString());
                    OracleDAL.InsertSyncRecord(dr["taskno"].ToString(), m_RecordType, type + "成功", 0);
                }
                else
                {
                    UpdateDispatchTable(dr["taskno"].ToString());
                    OracleDAL.InsertSyncRecord(dr["taskno"].ToString(), m_RecordType, strMsg, 1);
                }
            }

        }

        #region 派工添加（结转数据）
        /// <summary>
        /// 获取结转表没有的派工记录
        /// </summary>
        /// <returns></returns>
        DataTable GetDispatchInfoToWCAPP()
        {
            string factoryCode = ConfigurationManager.AppSettings["WCAPP"].ToString();
            string FactoryID = GetFactoryIDByFactoryCode(factoryCode);
            string WCAPPOperationName = ConfigurationManager.AppSettings["WCAPPOperationName"].ToString();
            string strSql = @"SELECT  csd.containerstepdispatchid taskNo,pb.productname partNo,p.description PRODUCTDESCRIPTION,p.productrevision,c.containername batchNo,
                                    LPAD (s.specno,4,'0') seqNo ,csd.qty COUNT,ut.attributevalue facCode,rd.resourcename weldNo,NULL welderNo,ws.workflowstepname stepname, 
                                    to_char( csd.plannedstartdate,'yyyy/mm/dd hh24:mi:ss') startTime,to_char(csd.plannedfinishdate,'yyyy/mm/dd hh24:mi:ss') endTime,csd.createdate,
                                    csd.factoryid
                                    FROM containerstepdispatch csd
                                    LEFT JOIN container c ON c.containerid=csd.containerid
                                    LEFT JOIN product p ON p.productid=c.productid
                                    LEFT JOIN productbase pb ON pb.productbaseid=p.productbaseid
                                    LEFT JOIN workflowstep ws ON  ws.workflowstepid=csd.workflowstepid
                                    LEFT JOIN specbase sb ON sb.specbaseid=ws.specbaseid
                                    LEFT JOIN spec s ON s.specid=NVL(sb.revofrcdid,ws.specid)
                                    LEFT JOIN Userattribute ut ON ut.parentid=csd.factoryid AND ut.userattributename='分厂代码'
                                    LEFT JOIN resourcedef rd ON rd.resourceid=csd.resourceid                                                     
                                    LEFT JOIN mes_senddispatch_table mst ON mst.taskno=csd.containerstepdispatchid                                    
                                    WHERE csd.isuse=0 AND mst.taskno IS NULL  and csd.factoryid='" + FactoryID + "'";
            string dateNode = ConfigurationManager.AppSettings["DateNode"];
            strSql += string.Format(" AND CSD.createdate>=sysdate-7", dateNode);//TO_DATE('{0}','yyyy/mm/dd hh24:mi:ss')
            strSql += " and rownum<1000 ";

            strSql += @" GROUP BY  csd.containerstepdispatchid ,pb.productname ,p.description ,p.productrevision,c.containername ,
                                s.specno ,csd.qty ,ut.attributevalue ,rd.resourcename ,ws.workflowstepname , --a.employeename ,
                                csd.plannedstartdate ,csd.plannedfinishdate,csd.factoryid,csd.createdate";
            return OracleHelper.Query (strSql).Tables[0];
        }

        /// <summary>
        /// WCAPP插入到中间结转表
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        Boolean InsertWCAPPTableSendDispatchOfRow(DataRow dr)
        {
            string insertSql = @"
                                        INSERT INTO MES_SENDDISPATCH_TABLE T (T.TASKNO,T.PARTNO,T.PRODUCTDESCRIPTION,T.PRODUCTREVISION,T.BATCHNO,T.SEQNO,
                                        T.STEPNAME,T.COUNT,T.FACCODE,T.WELDNO,T.WELDERNO,T.STARTTIME,t.endtime,Status,t.isintegration,t.factoryid) 
                                        VALUES(:TASKNO,:PARTNO,:PRODUCTDESCRIPTION,:PRODUCTREVISION,:BATCHNO,:SEQNO,:STEPNAME,:COUNT,:FACCODE,:WELDNO,
                                        :WELDERNO,to_date(:STARTTIME,'yyyy/mm/dd hh24:mi:ss'),to_date(:endtime,'yyyy/mm/dd hh24:mi:ss'),0,0,:FACTORYID)
                                        ";
            OracleParameter[] insertPara = new OracleParameter[14];
            insertPara[0] = OracleHelper.NewOracleParameter(":TASKNO", dr["TASKNO"], OracleType.VarChar);
            insertPara[1] = OracleHelper.NewOracleParameter(":PARTNO", dr["PARTNO"], OracleType.VarChar);
            insertPara[2] = OracleHelper.NewOracleParameter(":PRODUCTDESCRIPTION", dr["PRODUCTDESCRIPTION"], OracleType.VarChar);
            insertPara[3] = OracleHelper.NewOracleParameter(":PRODUCTREVISION", dr["PRODUCTREVISION"], OracleType.VarChar);
            insertPara[4] = OracleHelper.NewOracleParameter(":BATCHNO", dr["BATCHNO"], OracleType.VarChar);
            insertPara[5] = OracleHelper.NewOracleParameter(":SEQNO", dr["SEQNO"], OracleType.VarChar);
            insertPara[6] = OracleHelper.NewOracleParameter(":STEPNAME", dr["STEPNAME"], OracleType.VarChar);
            insertPara[7] = OracleHelper.NewOracleParameter(":COUNT", dr["COUNT"], OracleType.Number);
            insertPara[8] = OracleHelper.NewOracleParameter(":FACCODE", dr["FACCODE"], OracleType.VarChar);
            insertPara[9] = OracleHelper.NewOracleParameter(":WELDNO", dr["WELDNO"].ToString(), OracleType.VarChar);
            insertPara[10] = OracleHelper.NewOracleParameter(":WELDERNO", dr["WELDERNO"], OracleType.VarChar);
            insertPara[11] = OracleHelper.NewOracleParameter(":STARTTIME", dr["STARTTIME"], OracleType.VarChar);
            insertPara[12] = OracleHelper.NewOracleParameter(":endtime", dr["endtime"], OracleType.VarChar);
            insertPara[13] = OracleHelper.NewOracleParameter(":FACTORYID", dr["FACTORYID"], OracleType.VarChar);
            int i = OracleHelper.ExecuteSql(insertSql, insertPara);
            if (i > 0)
                return true;
            else
                return false;
        }

        /// <summary>
        /// 插入派工信息到数据结转表
        /// </summary>
        void InsertWCAPPTableSendDispatch()
        {
            DataTable dt = GetDispatchInfoToWCAPP();
            if (dt.Rows.Count == 0)
                return;
            foreach (DataRow row in dt.Rows)
            {
                //查询派到的人员，进行插入
                DataTable empDt = OracleHelper.Query(@"SELECT distinct e.employeename FROM containerstepdispatch csd
                                    LEFT JOIN containerstepdispatchdetail csdd ON csdd.containerstepdispatchid=csd.containerstepdispatchid
                                    LEFT JOIN employee e ON e.employeeid=NVL(csdd.workerid,csd.workerid)
                                    WHERE csd.containerstepdispatchid='" + row["taskNo"].ToString() + "'").Tables[0];
                foreach (DataRow empRow in empDt.Rows)
                {
                    row["welderNo"] = empRow["employeename"];
                    InsertWCAPPTableSendDispatchOfRow(row);
                }
            }
        }
        #endregion

        #region 派工修改（结转数据）
        /// <summary>
        /// 获取结转表中存在并派工修改的记录
        /// </summary>
        /// <returns></returns>
        DataTable GetDispatchOfUpdateToWCAPP()
        {
            string factoryCode = ConfigurationManager.AppSettings["WCAPP"].ToString();
            string FactoryID = GetFactoryIDByFactoryCode(factoryCode);
            string strSql = @"SELECT csd.containerstepdispatchid taskNo,csd.qty COUNT,rd.resourcename weldNo,e.employeename welderNo,
                                    to_char( csd.plannedstartdate,'yyyy/mm/dd hh24:mi:ss') startTime,to_char(csd.plannedfinishdate,'yyyy/mm/dd hh24:mi:ss') endTime 
                                    FROM containerstepdispatch csd
                                    LEFT JOIN resourcedef rd ON rd.resourceid=csd.resourceid
                                    LEFT JOIN EMPLOYEE E ON E.EMPLOYEEID=csd.WORKERID--工人 
                                    INNER JOIN mes_senddispatch_table mst ON mst.taskno=csd.containerstepdispatchid
                                    WHERE csd.isuse =0 AND (
                                    e.employeename<>mst.welderno OR rd.resourcename<>mst.weldno OR csd.qty<>mst.count OR mst.starttime<>csd.plannedstartdate 
                                    OR mst.endtime<>csd.plannedfinishdate ) AND csd.createdate>=SYSDATE-1 and csd.factoryid='" + FactoryID + "' and rownum<1001";
            return OracleHelper.Query (strSql).Tables[0];
        }
        /// <summary>
        /// 派工修改更新
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        Boolean UpdateDispatchOfRowToWCAPP(DataRow dr)
        {
            string strSql = @"
                                    UPDATE mes_senddispatch_table t SET t.count=:count,t.welderno=:welderno,t.weldno=:weldno,
                                    t.starttime=TO_DATE(:STARTTIME,'yyyy/mm/dd hh24:mi:ss'),t.endtime=TO_DATE(:endtime,'yyyy/mm/dd hh24:mi:ss'),t.isintegration=0,t.status=2
                                    WHERE t.taskno=:taskno
                                    ";
            OracleParameter[] insertPara = new OracleParameter[6];
            insertPara[0] = OracleHelper.NewOracleParameter(":count", dr["count"], OracleType.Number);
            insertPara[1] = OracleHelper.NewOracleParameter(":welderno", dr["welderno"], OracleType.VarChar);
            insertPara[2] = OracleHelper.NewOracleParameter(":weldno", dr["weldno"], OracleType.VarChar);
            insertPara[3] = OracleHelper.NewOracleParameter(":starttime", dr["starttime"].ToString (), OracleType.VarChar);
            insertPara[4] = OracleHelper.NewOracleParameter(":endtime", dr["endtime"].ToString (), OracleType.VarChar);
            insertPara[5] = OracleHelper.NewOracleParameter(":taskno", dr["taskno"], OracleType.VarChar);
            int i = OracleHelper.ExecuteSql(strSql, insertPara);
            if (i > 0)
                return true;
            else
                return false;
        }
        void UpdateWCAPPDispatchOfModify()
        {
            DataTable dt = GetDispatchOfUpdateToWCAPP();
            if (dt.Rows.Count == 0)
                return;
            foreach (DataRow row in dt.Rows)
            {
                UpdateDispatchOfRowToWCAPP(row);
            }
        }
        #endregion

        #region 派工删除（结转数据）
        /// <summary>
        /// 获取结转表有但已经删除的派工记录
        /// </summary>
        DataTable GetdispatchOfDeleteToWCAPP()
        {
            string factoryCode = ConfigurationManager.AppSettings["WCAPP"].ToString();
            string FactoryID = GetFactoryIDByFactoryCode(factoryCode);
            string strSql = @"SELECT mst.* FROM mes_senddispatch_table mst
                                    LEFT JOIN containerstepdispatch csd ON csd.containerstepdispatchid=mst.taskno
                                    WHERE csd.createdate>=SYSDATE-365 AND csd.isuse=1 AND mst.status!=1 and csd.factoryid='" + FactoryID + "'";
            strSql += " AND ROWNUM<1001 ";

            return OracleHelper.Query (strSql).Tables[0];
        }
        /// <summary>
        /// 派工删除更新
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        Boolean ModifyDispatchOfRowToWCAPP(DataRow dr, int status)
        {
            string updateSql = @"UPDATE mes_senddispatch_table t SET t.isintegration=0 ,t.status=:status WHERE t.taskno=:taskno";
            OracleParameter[] updatePara = new OracleParameter[2];
            updatePara[0] = OracleHelper.NewOracleParameter(":taskno", dr["taskno"], OracleType.VarChar);
            updatePara[1] = OracleHelper.NewOracleParameter(":status", status, OracleType.Number);
            int i = OracleHelper.ExecuteSql(updateSql, updatePara);
            if (i > 0)
                return true;
            else
                return false;
        }
        /// <summary>
        /// 派工删除后更新结转表
        /// </summary>
        void UpdateWCAPPDispatchOfDelete()
        {
            DataTable dt = GetdispatchOfDeleteToWCAPP();
            if (dt.Rows.Count == 0)
                return;
            foreach (DataRow row in dt.Rows)
            {
                ModifyDispatchOfRowToWCAPP(row, 1);
            }
        }
        #endregion

        /// <summary>
        /// 获取待推送的派工记录
        /// </summary>
        /// <returns></returns>
        DataTable GetWCAPPWaitDispatchInfo(string factoryid)
        {
            string strSql = @"SELECT * FROM mes_senddispatch_table t
                                    WHERE  t.isintegration=0 and t.starttime>=sysdate-100 and t.factoryid='" + factoryid + "'";
            strSql += " and rownum<1001 ";
            return OracleHelper.Query (strSql).Tables[0];
        }

        /// <summary>
        /// 给字典赋值
        /// </summary>
        /// <param name="strList"></param>
        /// <param name="dr"></param>
        void AddDctionary(ref Dictionary<string, string> strList, DataRow dr)
        {
            strList.Add("PartNo", dr["PARTNO"].ToString());//零件编号（图号）
            strList.Add("BatchNo", dr["batchNo"].ToString());//批次号（零件图号/批次序号）
            strList.Add("SeqNo", dr["seqNo"].ToString());//工序号（4位，不够前面补0）
            strList.Add("Count", dr["count"].ToString());//派工数量
            strList.Add("FacCode", dr["facCode"].ToString());//分厂代码（MES从PDM里面接收）
            strList.Add("WeldNo", dr["weldNo"].ToString());//设备编号
            strList.Add("WelderNo", dr["welderNo"].ToString());//员工编号（8位）
            strList.Add("StartTime", dr["startTime"].ToString());//计划起始时间
            strList.Add("EndTime", dr["endTime"].ToString());//计划终止时间
        }

        /// <summary>
        /// 创建xml字符串
        /// </summary>
        /// <param name="strList"></param>
        /// <returns></returns>
        private string CreateWCAPPXML(Dictionary<string, string> strList, int type)
        {

            XmlDocument doc = new XmlDocument();
            doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", ""));
            XmlNode ReqNode = doc.CreateElement("ReqMsg");
            XmlNode headerNode = doc.CreateElement("header");
            XmlNode senderNode = doc.CreateElement("sendSysName");
            senderNode.InnerText = "APP_MES";
            XmlNode rcvNode = doc.CreateElement("rcvSysName");
            rcvNode.InnerText = "APP_WCAPP";
            XmlNode extNode = doc.CreateElement("extConfig");
            extNode.AppendChild(doc.CreateElement("isReTry"));
            extNode.LastChild.InnerText = "false";

            headerNode.AppendChild(senderNode);
            headerNode.AppendChild(rcvNode);
            headerNode.AppendChild(extNode);
            ReqNode.AppendChild(headerNode);
            XmlNode documentNode = doc.CreateElement("document");

            string strData = "";
            if (type == 0) //添加
            {
                strData = "<AddTask>";
            }
            else if (type == 1)//删除
            {
                strData = "<DeleteTask>";
            }
            else if (type == 2)//修改
            {
                strData = "<UpdateTask>";
            }


            foreach (KeyValuePair<string, string> _key in strList)
            {
                strData = string.Format("{0}<{1}>{2}</{1}>", strData, _key.Key, _key.Value);
            }

            if (type == 0) //添加
            {
                strData += "</AddTask>";
            }
            else if (type == 1)//删除
            {
                strData += "</DeleteTask>";
            }
            else if (type == 2)//修改
            {
                strData += "</UpdateTask>";
            }

            documentNode.AppendChild(doc.CreateCDataSection(strData));
            ReqNode.AppendChild(documentNode);
            doc.AppendChild(ReqNode);
            return doc.InnerXml;
        }
        #endregion


        #region TDM数据结转 Create YangJiang 20180702
        /// <summary>
        /// 推送试车派工信息到TDM 
        /// </summary>
        public void RunSendDispatchSyncToTDMSCTask()
        {
            string factoryCode = ConfigurationManager.AppSettings["TDM"].ToString();
            string FactoryID = GetFactoryIDByFactoryCode(factoryCode);
            DataTable dt = GetTDMWaitDispatchInfo(FactoryID, "2");
            if (dt.Rows.Count == 0)
            {
                // LogHelp.WriteLog("没有可处理的试车任务信息记录");
                return;
            }
            foreach (DataRow dr in dt.Rows)
            {
                LogHelp.WriteLog("处理试车任务记录开始" + dr["taskNo"]);
                Dictionary<string, string> strList = new Dictionary<string, string>();
                strList.Add("TaskNo", dr["TASKNO"].ToString());//任务(派工)ID
                string strMsg = "";
                string type = "";

                type = "试车任务信息添加";
                AddTestTaskDctionary(ref strList, dr);
                string strXml = CreateTDMXML(strList, 0);
                LogHelp.WriteLog("推送的XML:" + strXml);
                TDMService.MESServer mm = new TDMService.MESServer();
                try
                {
                    strMsg = mm.SynchTestTask(strXml);//
                }
                catch (Exception ex)
                {
                    LogHelp.WriteLog(ex.Message);
                }



                LogHelp.WriteLog("返回的XML:" + strMsg);
                if (GetRcvXML(strMsg))
                {
                    UpdateDispatchTable(dr["taskno"].ToString());
                    OracleDAL.InsertSyncRecord(dr["taskno"].ToString(), "SendTDMDispatchInfo", type + "成功", 0);
                }
                else
                {
                    UpdateDispatchTable(dr["taskno"].ToString());
                    OracleDAL.InsertSyncRecord(dr["taskno"].ToString(), "SendTDMDispatchInfo", strMsg, 1);
                }
            }

        }

        /// <summary>
        /// 推送部件试车派工信息到TDM 
        /// </summary>
        public void RunSendDispatchSyncToTDMPartTask()
        {
            string factoryCode = ConfigurationManager.AppSettings["TDM"].ToString();
            string FactoryID = GetFactoryIDByFactoryCode(factoryCode);
            DataTable dt = GetTDMWaitDispatchInfo(FactoryID, "1");
            if (dt.Rows.Count == 0)
            {
                // LogHelp.WriteLog("没有可处理的部件试车信息记录");
                return;
            }
            foreach (DataRow dr in dt.Rows)
            {
                LogHelp.WriteLog("部件试车信息记录开始" + dr["taskNo"]);
                Dictionary<string, string> strList = new Dictionary<string, string>();
                strList.Add("TaskNo", dr["TASKNO"].ToString());//任务(派工)ID
                string strMsg = "";
                string type = "";

                type = "部件试车任务添加";
                AddPartTaskDctionary(ref strList, dr);
                string strXml = CreateTDMXML(strList, 1);
                LogHelp.WriteLog("推送的XML:" + strXml);
                TDMService.MESServer mm = new TDMService.MESServer();
                try
                {
                    strMsg = mm.SynchPartTask(strXml);
                }
                catch (Exception ex)
                {
                    LogHelp.WriteLog(ex.Message);
                }



                LogHelp.WriteLog("返回的XML:" + strMsg);
                if (GetRcvXML(strMsg))
                {
                    UpdateDispatchTable(dr["taskno"].ToString());
                    OracleDAL.InsertSyncRecord(dr["taskno"].ToString(), "SendTDMDispatchInfo", type + "成功", 0);
                }
                else
                {
                    UpdateDispatchTable(dr["taskno"].ToString());
                    OracleDAL.InsertSyncRecord(dr["taskno"].ToString(), "SendTDMDispatchInfo", strMsg, 1);
                }
            }

        }

        #region 派工添加（结转数据）
        /// <summary>
        /// 获取结转表没有的派工记录(工序类型为'试验')
        /// </summary>
        /// <returns></returns>
        DataTable GetPartDispatchInfoToTDM()
        {
            string factoryCode = ConfigurationManager.AppSettings["TDM"].ToString();
            string FactoryID = GetFactoryIDByFactoryCode(factoryCode);
            string
                strSql = @" SELECT distinct csd.containerstepdispatchid TASKNO,pb.productname PARTNO,p1.description PRODUCTDESCRIPTION,p1.productrevision,c.containername BATCHNO,
                                    c.containerid,LPAD(s.specno,4,'0') SEQNO,wfs1.workflowstepname STEPNAME,csd.qty COUNT,ut.attributevalue FACCODE,rd.resourcename WELDNO,
                                    e.employeename WELDERNO,csd.factoryid, LPAD(si.Stepno,4,'0') MESSTEPNO,si.Description MESSTEP,wf1.workflowrevision,m.mfgordername DDH,
                                    wfb.workflowname PROCESS_NO,pf.productfamilyname MODELCODE,decode(pf.familytype,'1','批产','2','主研','3','参研','')ENGINESTATE,
                                    p1.materialcode BOMCODE,wfs.workflowstepname PHASENAME,m.plannedstartdate DDPLANSTARTTIME,m.plannedcompletiondate DDPLANENDTIME,
                                    ep.containerno PARTSN,ep.containerno ||'-'|| wfs1.workflowstepname ||'-'|| si.Description NAME,wf1.item_id WORKFLOWNUM,ua.attributevalue ENGINECODE,
                                    to_char( csd.plannedstartdate,'yyyy/mm/dd hh24:mi:ss') STARTTIME,to_char(csd.plannedfinishdate,'yyyy/mm/dd hh24:mi:ss') ENDTIME, 
                                    '试验' TASKTYPE
                                    FROM containerstepdispatch csd
                                    LEFT JOIN containercurrentinfo c ON c.containerid=csd.containerid
                                    LEFT JOIN mfgorder m ON m.mfgorderid=c.mfgorderid
                                       left join productbase pb2 on pb2.productbaseid=m.productbaseid
                                    LEFT JOIN product p ON p.productid=nvl(pb2.revofrcdid,m.productid)
                                   
                                  
                                    LEFT JOIN Userattribute ua ON ua.parentid=m.mfgorderid  AND ua.userattributename='发动机'
                                    LEFT JOIN Userattribute ut ON ut.parentid=csd.factoryid AND ut.userattributename='分厂代码'
                                    LEFT JOIN enginepartplan ep ON ep.containerid=c.containerid
                                    LEFT JOIN workflowstep wfs ON wfs.workflowstepid=ep.workflowstepid 
                                    LEFT JOIN product p1 ON p1.productid=c.productid
                                    LEFT JOIN workflowproductfamilylist wpfl ON wpfl.workflowid=p.workflowid
                                    LEFT JOIN productfamily pf ON pf.productfamilyid=wpfl.productfamilylistid
                                    LEFT JOIN productbase pb ON pb.productbaseid=p1.productbaseid
                                    LEFT JOIN Workflowstep wfs1 ON csd.workflowstepid=wfs1.workflowstepid
                                    LEFT JOIN specbase sb ON sb.specbaseid=wfs1.specbaseid
                                    LEFT JOIN spec s ON s.specid=NVL(sb.revofrcdid,wfs1.specid)
                                    LEFT JOIN stepinfo SI ON si.Stepinfoid=csd.stepinfoid
                                    LEFT JOIN spectype st ON st.spectypeid=si.Spectypeid 
                                    LEFT JOIN Workflow wf1 ON wf1.workflowid=wfs1.workflowid
                                    LEFT JOIN Workflowbase wfb ON wfb.workflowbaseid=wf1.workflowbaseid
                                    LEFT JOIN resourcedef rd ON rd.resourceid=csd.resourceid
                                    LEFT JOIN EMPLOYEE E ON E.EMPLOYEEID=csd.WORKERID
                                    LEFT JOIN mes_senddispatch_table mst ON mst.taskno=csd.containerstepdispatchid                            
                                    WHERE csd.isuse=0 AND mst.taskno IS NULL AND st.spectypename='试验'  
                                    AND csd.factoryid='" + FactoryID + "'";
            string dateNode = ConfigurationManager.AppSettings["DateNode"];
            strSql += string.Format(" AND CSD.createdate>=TO_DATE('{0}','yyyy/mm/dd hh24:mi:ss')", dateNode);
            return OracleHelper.Query (strSql).Tables[0];
        }

        /// <summary>
        /// 获取结转表没有的派工记录(试车)
        /// </summary>
        /// <returns></returns>
        DataTable GetSCDispatchInfoToTDM()
        {
            string factoryCode = ConfigurationManager.AppSettings["TDM"].ToString();
            string FactoryID = GetFactoryIDByFactoryCode(factoryCode);
            string
                strSql = @" SELECT * FROM (SELECT distinct csd.containerstepdispatchid TASKNO,pb.productname PARTNO,p1.description PRODUCTDESCRIPTION,p1.productrevision,
                                    c.containername BATCHNO,c.containerid,LPAD(s.specno,4,'0') SEQNO,wfs1.workflowstepname STEPNAME,csd.qty COUNT,ut.attributevalue FACCODE,
                                    rd.resourcename WELDNO,e.employeename WELDERNO,to_char( csd.plannedstartdate,'yyyy/mm/dd hh24:mi:ss') STARTTIME,ua.attributevalue ENGINECODE,
                                    to_char(csd.plannedfinishdate,'yyyy/mm/dd hh24:mi:ss') ENDTIME,csd.factoryid, LPAD(si.Stepno,4,'0') MESSTEPNO,si.Description MESSTEP,
                                    wf1.workflowrevision,wfb.workflowname PROCESS_NO,m.mfgordername DDH,pf.productfamilyname MODELCODE,m.plannedcompletiondate DDPLANENDTIME,
                                    decode(pf.familytype,'1','批产','2','主研','3','参研','')ENGINESTATE,p1.materialcode BOMCODE,wfs.workflowstepname PHASENAME,
                                    ep.containerno PARTSN, SUBSTR(wfs.workflowstepname,6,LENGTH(wfs.workflowstepname)-1)TASKTYPE,wf1.item_id WORKFLOWNUM,
                                    ep.containerno ||'-'|| wfs1.workflowstepname ||'-'|| si.Description NAME,m.plannedstartdate DDPLANSTARTTIME,
                                    Row_number()OVER(PARTITION BY csd.containerid ORDER BY csd.containerid) rn 
                                    FROM containerstepdispatch csd
                                    LEFT JOIN containercurrentinfo c ON c.containerid=csd.containerid
                                    LEFT JOIN mfgorder m ON m.mfgorderid=c.mfgorderid
                                        left join productbase pb2 on pb2.productbaseid=m.productbaseid
                                    LEFT JOIN product p ON p.productid=nvl(pb2.revofrcdid,m.productid)
                                   
                                   
                                    LEFT JOIN Userattribute ua ON ua.parentid=m.mfgorderid AND ua.userattributename='发动机'
                                    LEFT JOIN Userattribute ut ON ut.parentid=csd.factoryid AND ut.userattributename='分厂代码'
                                    LEFT JOIN enginepartplan ep ON ep.containerid=c.containerid
                                    LEFT JOIN workflowstep wfs ON wfs.workflowstepid=ep.workflowstepid 
                                    LEFT JOIN product p1 ON p1.productid=c.productid
                                     LEFT JOIN workflowproductfamilylist wpfl ON wpfl.workflowid=p.workflowid
                                    LEFT JOIN productfamily pf ON pf.productfamilyid=wpfl.productfamilylistid
                                    LEFT JOIN productbase pb ON pb.productbaseid=p1.productbaseid
                                    LEFT JOIN Workflowstep wfs1 ON csd.workflowstepid=wfs1.workflowstepid
                                    LEFT JOIN specbase sb ON sb.specbaseid=wfs1.specbaseid
                                    LEFT JOIN spec s ON s.specid=NVL(sb.revofrcdid,wfs1.specid)
                                    LEFT JOIN stepinfo SI ON si.Stepinfoid=csd.stepinfoid
                                    LEFT JOIN spectype st ON st.spectypeid=si.Spectypeid 
                                    LEFT JOIN Workflow wf1 ON wf1.workflowid=wfs1.workflowid
                                    LEFT JOIN Workflowbase wfb ON wfb.workflowbaseid=wf1.workflowbaseid
                                    LEFT JOIN resourcedef rd ON rd.resourceid=csd.resourceid
                                    LEFT JOIN EMPLOYEE E ON E.EMPLOYEEID=csd.WORKERID--工人 
                                    LEFT JOIN mes_senddispatch_table mst ON mst.taskno=csd.containerstepdispatchid                            
                                    WHERE csd.isuse=0 AND mst.taskno IS NULL AND wfs.workflowstepname LIKE '%试车%' 
                                    AND csd.factoryid='" + FactoryID + "'";
            string dateNode = ConfigurationManager.AppSettings["DateNode"];
            strSql += string.Format(" AND CSD.createdate>=TO_DATE('{0}','yyyy/mm/dd hh24:mi:ss')", dateNode);
            strSql += ") WHERE rn = 1";
            return OracleHelper.Query (strSql).Tables[0];
        }

        /// <summary>
        /// TDA数据插入到终检结转表 add YangJiang 20180702
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        Boolean InsertTDMTableSendDispatchOfRow(DataRow dr)
        {
            string insertSql = @"
                                        INSERT INTO MES_SENDDISPATCH_TABLE T (T.TASKNO,T.PARTNO,T.PRODUCTDESCRIPTION,T.PRODUCTREVISION,T.BATCHNO,T.SEQNO,
                                        T.STEPNAME,T.COUNT,T.FACCODE,T.WELDNO,T.WELDERNO,T.STARTTIME,t.endtime,Status,t.isintegration,
                                        FACTORYID,MESSTEPNO,MESSTEP,WORKFLOWREVISION,PROCESS_NO,DDH,MODELCODE,ENGINESTATE,BOMCODE,PHASENAME,TASKTYPE,NAME,PARTSN,
                                        DDPLANSTARTTIME,DDPLANENDTIME,CONTAINERID,WORKFLOWNUM,ENGINECODE) 
                                        VALUES(:TASKNO,:PARTNO,:PRODUCTDESCRIPTION,
                                        :PRODUCTREVISION,:BATCHNO,:SEQNO,:STEPNAME,:COUNT,:FACCODE,:WELDNO,:WELDERNO,to_date(:STARTTIME,'yyyy/mm/dd hh24:mi:ss'),
                                        to_date(:endtime,'yyyy/mm/dd hh24:mi:ss'),0,0,
                                        :FACTORYID,:MESSTEPNO,:MESSTEP,:WORKFLOWREVISION,:PROCESS_NO,:DDH,:MODELCODE,:ENGINESTATE,:BOMCODE,:PHASENAME,:TASKTYPE,:NAME,:PARTSN,
                                        to_date(:DDPLANSTARTTIME,'yyyy/mm/dd hh24:mi:ss'),to_date(:DDPLANENDTIME,'yyyy/mm/dd hh24:mi:ss'),:CONTAINERID,:WORKFLOWNUM,:ENGINECODE) ";
            OracleParameter[] insertPara = new OracleParameter[31];
            insertPara[0] = OracleHelper.NewOracleParameter(":TASKNO", dr["TASKNO"], OracleType.VarChar);
            insertPara[1] = OracleHelper.NewOracleParameter(":PARTNO", dr["PARTNO"], OracleType.VarChar);
            insertPara[2] = OracleHelper.NewOracleParameter(":PRODUCTDESCRIPTION", dr["PRODUCTDESCRIPTION"], OracleType.VarChar);
            insertPara[3] = OracleHelper.NewOracleParameter(":PRODUCTREVISION", dr["PRODUCTREVISION"], OracleType.VarChar);
            insertPara[4] = OracleHelper.NewOracleParameter(":BATCHNO", dr["BATCHNO"], OracleType.VarChar);
            insertPara[5] = OracleHelper.NewOracleParameter(":SEQNO", dr["SEQNO"], OracleType.VarChar);
            insertPara[6] = OracleHelper.NewOracleParameter(":STEPNAME", dr["STEPNAME"], OracleType.VarChar);
            insertPara[7] = OracleHelper.NewOracleParameter(":COUNT", dr["COUNT"], OracleType.VarChar);
            insertPara[8] = OracleHelper.NewOracleParameter(":FACCODE", dr["FACCODE"], OracleType.VarChar);
            insertPara[9] = OracleHelper.NewOracleParameter(":WELDNO", dr["WELDNO"].ToString(), OracleType.VarChar);
            insertPara[10] = OracleHelper.NewOracleParameter(":WELDERNO", dr["WELDERNO"], OracleType.VarChar);
            insertPara[11] = OracleHelper.NewOracleParameter(":STARTTIME", dr["STARTTIME"], OracleType.VarChar);// modify by longb 2023-07-24
            insertPara[12] = OracleHelper.NewOracleParameter(":endtime", dr["ENDTIME"], OracleType.VarChar);// modify by longb 2023-07-24

            insertPara[13] = OracleHelper.NewOracleParameter(":CONTAINERID", dr["CONTAINERID"], OracleType.VarChar);

            insertPara[14] = OracleHelper.NewOracleParameter(":FACTORYID", dr["FACTORYID"], OracleType.VarChar);
            insertPara[15] = OracleHelper.NewOracleParameter(":MESSTEPNO", dr["MESSTEPNO"], OracleType.VarChar);
            insertPara[16] = OracleHelper.NewOracleParameter(":MESSTEP", dr["MESSTEP"], OracleType.VarChar);
            insertPara[17] = OracleHelper.NewOracleParameter(":WORKFLOWREVISION", dr["WORKFLOWREVISION"], OracleType.VarChar);
            insertPara[18] = OracleHelper.NewOracleParameter(":PROCESS_NO", dr["PROCESS_NO"], OracleType.VarChar);
            insertPara[19] = OracleHelper.NewOracleParameter(":DDH", dr["DDH"], OracleType.VarChar);
            insertPara[20] = OracleHelper.NewOracleParameter(":MODELCODE", dr["MODELCODE"], OracleType.VarChar);
            insertPara[21] = OracleHelper.NewOracleParameter(":ENGINESTATE", dr["ENGINESTATE"], OracleType.VarChar);
            insertPara[22] = OracleHelper.NewOracleParameter(":BOMCODE", dr["BOMCODE"], OracleType.VarChar);
            insertPara[23] = OracleHelper.NewOracleParameter(":PHASENAME", dr["PHASENAME"], OracleType.VarChar);
            insertPara[24] = OracleHelper.NewOracleParameter(":TASKTYPE", dr["TASKTYPE"], OracleType.VarChar);
            insertPara[25] = OracleHelper.NewOracleParameter(":NAME", dr["NAME"], OracleType.VarChar);
            insertPara[26] = OracleHelper.NewOracleParameter(":PARTSN", dr["PARTSN"], OracleType.VarChar);
            insertPara[27] = OracleHelper.NewOracleParameter(":DDPLANSTARTTIME", dr["DDPLANSTARTTIME"], OracleType.VarChar);// modify by longb 2023-07-24
            insertPara[28] = OracleHelper.NewOracleParameter(":DDPLANENDTIME", dr["DDPLANENDTIME"], OracleType.VarChar);// modify by longb 2023-07-24
            //insertPara[29] = OracleHelper.NewOracleParameter(":PARTSNAME", dr["PRODUCTDESCRIPTION"], OracleType.VarChar); wangjh 20181129 注释
            insertPara[29] = OracleHelper.NewOracleParameter(":WORKFLOWNUM", dr["WORKFLOWNUM"], OracleType.VarChar);
            insertPara[30] = OracleHelper.NewOracleParameter(":ENGINECODE", dr["ENGINECODE"], OracleType.VarChar);
            int i = OracleHelper.ExecuteSql(insertSql, insertPara);
            if (i > 0)
                return true;
            else
                return false;
        }

        /// <summary>
        /// 插入派工信息到数据结转表
        /// </summary>
        void InsertTDMTableSendDispatch()
        {
            DataTable dt = GetPartDispatchInfoToTDM();

            foreach (DataRow row in dt.Rows)
            {
                InsertTDMTableSendDispatchOfRow(row);
            }
            dt = GetSCDispatchInfoToTDM();

            foreach (DataRow row in dt.Rows)
            {
                InsertTDMTableSendDispatchOfRow(row);
            }
        }
        #endregion

        /// <summary>
        /// 给字典赋值(试车任务信息)
        /// </summary>
        /// <param name="strList"></param>
        /// <param name="dr"></param>
        void AddTestTaskDctionary(ref Dictionary<string, string> strList, DataRow dr)
        {
            strList.Add("DDH", dr["DDH"].ToString());//订单号
            strList.Add("MODELCODE", dr["MODELCODE"].ToString());//机型
            strList.Add("ENGINECODE", dr["ENGINECODE"].ToString());//发动机编号
            strList.Add("PARTNUM", dr["PARTNO"].ToString());//零件号
            strList.Add("BOMCODE", dr["BOMCODE"].ToString());//物料编码
            strList.Add("ENGINESTATE", dr["ENGINESTATE"].ToString());//机型类型
            strList.Add("DDPLANSTARTTIME", dr["DDPLANSTARTTIME"].ToString());//订单计划开始时间
            strList.Add("DDPLANENDTIME", dr["DDPLANENDTIME"].ToString());//订单计划完成时间
            strList.Add("MESID", dr["TASKNO"].ToString());//任务ID
            strList.Add("PHASENAME", dr["PHASENAME"].ToString());//阶段名称
            strList.Add("CONTAINERID", dr["CONTAINERID"].ToString());//批次ID
            strList.Add("STARTTIME", dr["STARTTIME"].ToString());//计划开始时间
            strList.Add("ENDTIME", dr["ENDTIME"].ToString());//计划完成时间
            strList.Add("TASKTYPE", dr["TASKTYPE"].ToString());//试车种类名称
            strList.Add("GYGCNO", dr["WORKFLOWNUM"].ToString());//工艺规程编号
            strList.Add("GYGCNAME", dr["PROCESS_NO"].ToString());//工艺规程名称
        }

        /// <summary>
        /// 给字典赋值(部件试车任务信息)
        /// </summary>
        /// <param name="strList"></param>
        /// <param name="dr"></param>
        void AddPartTaskDctionary(ref Dictionary<string, string> strList, DataRow dr)
        {
            strList.Add("MESID", dr["TASKNO"].ToString());//任务ID
            strList.Add("NAME", dr["NAME"].ToString());//任务名称
            strList.Add("DDH", dr["DDH"].ToString());//订单号
            strList.Add("MODELCODE", dr["MODELCODE"].ToString());//机型
            strList.Add("ENGINECODE", dr["ENGINECODE"].ToString());//发动机编号
            strList.Add("PHASENAME", dr["PHASENAME"].ToString());//阶段名称
            strList.Add("CONTAINERID", dr["CONTAINERID"].ToString());//批次ID
            strList.Add("PARTNUM", dr["PARTNO"].ToString());//零件号(部件号)
            strList.Add("BOMCODE", dr["BOMCODE"].ToString());//物料编码
            strList.Add("ENGINESTATE", dr["ENGINESTATE"].ToString());//机型类型
            strList.Add("DDPLANSTARTTIME", dr["DDPLANSTARTTIME"].ToString());//订单计划开始时间
            strList.Add("DDPLANENDTIME", dr["DDPLANENDTIME"].ToString());//订单计划完成时间
            strList.Add("PARTSN", dr["PARTSN"].ToString());//部件编号
            strList.Add("PARTSNAME", dr["productdescription"].ToString());//部件名称
            strList.Add("MESOPNO", dr["seqno"].ToString());//工序号
            strList.Add("MESOP", dr["stepname"].ToString());//工序名称
            strList.Add("MESSTEPNO", dr["messtepno"].ToString());//工步号
            strList.Add("MESSTEP", dr["MESSTEP"].ToString());//工步名称
            strList.Add("STARTTIME", dr["STARTTIME"].ToString());//计划开始时间
            strList.Add("ENDTIME", dr["ENDTIME"].ToString());//计划完成时间 
            strList.Add("GYGCBH", dr["WORKFLOWNUM"].ToString());//工艺规程编号
            strList.Add("GYGCMC", dr["PROCESS_NO"].ToString());//工艺规程名称 
        }

        /// <summary>
        /// 创建试车任务信息xml字符串
        /// </summary>
        /// <param name="strList"></param>
        /// <returns></returns>
        private string CreateTDMXML(Dictionary<string, string> strList, int type)
        {

            XmlDocument doc = new XmlDocument();
            doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", ""));
            XmlNode ReqNode = doc.CreateElement("ReqMsg");
            XmlNode headerNode = doc.CreateElement("header");
            XmlNode senderNode = doc.CreateElement("sendSysName");
            senderNode.InnerText = "APP_MES";
            XmlNode rcvNode = doc.CreateElement("rcvSysName");
            rcvNode.InnerText = "APP_TDM";

            XmlNode documentNode = doc.CreateElement("document");

            string strData = "";
            if (type == 0) //试车
            {
                strData = "<SCTask>";
            }
            else if (type == 1)//部件
            {
                strData = "<PartTask>";
            }



            foreach (KeyValuePair<string, string> _key in strList)
            {
                strData += string.Format("<{0}>{1}</{0}>", _key.Key, _key.Value);
            }

            if (type == 0) //试车
            {
                strData += "</SCTask>";
            }
            else if (type == 1)//部件
            {
                strData += "</PartTask>";
            }

            documentNode.AppendChild(doc.CreateCDataSection(strData));
            ReqNode.AppendChild(documentNode);
            doc.AppendChild(ReqNode);
            return doc.InnerXml;
        }

        /// <summary>
        /// 获取待推送的派工记录
        /// </summary>
        /// <returns></returns>
        DataTable GetTDMWaitDispatchInfo(string factoryid, string TDMtype)
        {
            string strSql = @"SELECT * FROM mes_senddispatch_table t 
                                     left join writetoerprecord wt on wt.recordid=t.taskno
                                    WHERE t.isintegration=0 and wt.recordid is null and t.factoryid='" + factoryid + "'";
            if (TDMtype == "1")
            {
                strSql += " and t.TASKTYPE='试验'";
            }
            if (TDMtype == "2")
            {
                strSql += " and t.TASKTYPE like'%试车%'";
            }

            return OracleHelper.Query (strSql).Tables[0];
        }

        #endregion


        #region ZDSC数据结转 Create YangJiang 20180709
        /// <summary>
        /// 推送作动筒信息到ZDSC 
        /// </summary>
        public void RunSendDispatchSyncToZDSC()
        {
            string factoryCode = ConfigurationManager.AppSettings["ZDSC"].ToString();
            string FactoryID = GetFactoryIDByFactoryCode(factoryCode);
            DataTable dt = GetZDSCWaitDispatchInfo(FactoryID);
            if (dt.Rows.Count == 0)
            {
                LogHelp.WriteLog("没有可处理的作动筒信息记录");
                return;
            }
            foreach (DataRow dr in dt.Rows)
            {
                LogHelp.WriteLog("处理作动筒信息记录开始" + dr["taskNo"]);
                Dictionary<string, string> strList = new Dictionary<string, string>();
                // strList.Add("TaskNo", dr["TASKNO"].ToString());//任务(派工)ID
                string strMsg = "";
                string type = "";

                type = "试车任务信息添加";
                AddZDSCDctionary(ref strList, dr);
                string strXml = CreateZDSCXML(strList);
                LogHelp.WriteLog("推送的ZDSC的XML:" + strXml);
                // ZDSCService..WebService mm = new ZDSCService.WebService();//需要换作ZDSC的服务
                ZDSCService.MESServices mm = new ZDSCService.MESServices();//需要换作ZDSC的服务
                try
                {
                    strMsg = mm.GetMESJob(strXml);
                }
                catch (Exception ex)
                {
                    LogHelp.WriteLog(ex.Message);
                }



                LogHelp.WriteLog("ZDSC返回的XML:" + strMsg);
                if (GetRcvXML(strMsg))
                {
                    UpdateDispatchTable(dr["taskno"].ToString());
                    OracleDAL.InsertSyncRecord(dr["taskno"].ToString(), "SendZDSCDispatchInfo", type + "成功", 0);
                }
                else
                {
                    UpdateDispatchTable(dr["taskno"].ToString());
                    OracleDAL.InsertSyncRecord(dr["taskno"].ToString(), "SendZDSCDispatchInfo", strMsg, 1);
                }
            }

        }


        #region 派工添加（结转数据）

        /// <summary>
        /// 获取结转表没有的派工记录(ZDSC)
        /// </summary>
        /// <returns></returns>
        DataTable GetDispatchInfoToZDSC()
        {
            string factoryCode = ConfigurationManager.AppSettings["ZDSC"].ToString();
            string FactoryID = GetFactoryIDByFactoryCode(factoryCode);
            string ZDSCOperationName = ConfigurationManager.AppSettings["ZDSCOperationName"].ToString();
            string
                strSql = @" SELECT csd.containerstepdispatchid TASKNO,pb.productname PARTNO,p.description PRODUCTDESCRIPTION,wf.item_id WORKFLOWNUM,
                                wfb.workflowname PROCESS_NO,cci.planqty COUNT,cci.containername BATCHNO,cci.containerid,ut.attributevalue FACCODE,
                                csd.factoryid,m.mfgorderid DDH,wf.workflowrevision,p.productrevision,
                                to_char( csd.plannedstartdate,'yyyy/mm/dd hh24:mi:ss') STARTTIME,to_char(csd.plannedfinishdate,'yyyy/mm/dd hh24:mi:ss') ENDTIME
                                FROM containerstepdispatch csd
                                LEFT JOIN containercurrentinfo cci ON cci.containerid=csd.containerid
                                LEFT JOIN mfgorder m ON m.mfgorderid=cci.mfgorderid
                                LEFT JOIN product p ON p.productid=cci.productid
                                LEFT JOIN productbase pb ON pb.productbaseid=p.productbaseid
                                LEFT JOIN Workflowstep wfs ON csd.workflowstepid=wfs.workflowstepid
                                LEFT JOIN workflow wf ON wf.workflowid=wfs.workflowid
                                LEFT JOIN Workflowbase wfb ON wfb.workflowbaseid=wf.workflowbaseid
                                LEFT JOIN Userattribute ut ON ut.parentid=csd.factoryid AND ut.userattributename='分厂代码'
                                LEFT JOIN EMPLOYEE E ON E.EMPLOYEEID=csd.WORKERID                                    
                                LEFT JOIN sessionvalues sv ON sv.employeeid=e.employeeid
                                LEFT JOIN operation o ON o.operationid=sv.operationid--查找工种为生产线的派工数据
                                LEFT JOIN mes_senddispatch_table mst ON mst.taskno=csd.containerstepdispatchid
                                WHERE csd.isuse=0 AND mst.taskno IS NULL
                                AND cci.containerid IS NOT NULL AND o.operationname='" + ZDSCOperationName + "' and csd.factoryid='" + FactoryID + "'";
            string dateNode = ConfigurationManager.AppSettings["DateNode"];
            strSql += string.Format(" AND CSD.createdate>=TO_DATE('{0}','yyyy/mm/dd hh24:mi:ss')", dateNode);
            //strSql += " and rownum<5";//测试用 
            return OracleHelper.Query(strSql).Tables[0];
        }

        /// <summary>
        /// TDA数据插入到终检结转表 add YangJiang 20180702
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        Boolean InsertZDSCTableSendDispatchOfRow(DataRow dr)
        {
            string insertSql = @"
                                        INSERT INTO MES_SENDDISPATCH_TABLE T (T.TASKNO,T.PARTNO,T.PRODUCTDESCRIPTION,T.PRODUCTREVISION,T.BATCHNO,
                                        T.COUNT,T.FACCODE,T.STARTTIME,t.endtime,Status,t.isintegration,
                                        FACTORYID,WORKFLOWREVISION,PROCESS_NO,DDH,CONTAINERID,WORKFLOWNUM) 
                                        VALUES(:TASKNO,:PARTNO,:PRODUCTDESCRIPTION,
                                        :PRODUCTREVISION,:BATCHNO,:COUNT,:FACCODE,to_date(:STARTTIME,'yyyy/mm/dd hh24:mi:ss'),
                                        to_date(:endtime,'yyyy/mm/dd hh24:mi:ss'),0,0,
                                        :FACTORYID,:WORKFLOWREVISION,:PROCESS_NO,:DDH,:CONTAINERID,:WORKFLOWNUM) ";//update:Wangjh 20180713 去掉PARTSNAME
            OracleParameter[] insertPara = new OracleParameter[15];
            insertPara[0] = OracleHelper.NewOracleParameter(":TASKNO", dr["TASKNO"], OracleType.VarChar);
            insertPara[1] = OracleHelper.NewOracleParameter(":PARTNO", dr["PARTNO"], OracleType.VarChar);
            insertPara[2] = OracleHelper.NewOracleParameter(":PRODUCTDESCRIPTION", dr["PRODUCTDESCRIPTION"], OracleType.VarChar);
            insertPara[3] = OracleHelper.NewOracleParameter(":PRODUCTREVISION", dr["PRODUCTREVISION"], OracleType.VarChar);
            insertPara[4] = OracleHelper.NewOracleParameter(":BATCHNO", dr["BATCHNO"], OracleType.VarChar);
            insertPara[5] = OracleHelper.NewOracleParameter(":COUNT", dr["COUNT"], OracleType.Number);
            insertPara[6] = OracleHelper.NewOracleParameter(":FACCODE", dr["FACCODE"], OracleType.VarChar);
            insertPara[7] = OracleHelper.NewOracleParameter(":STARTTIME", dr["STARTTIME"], OracleType.DateTime);
            insertPara[8] = OracleHelper.NewOracleParameter(":endtime", dr["ENDTIME"], OracleType.DateTime);
            insertPara[9] = OracleHelper.NewOracleParameter(":CONTAINERID", dr["CONTAINERID"], OracleType.VarChar);
            insertPara[10] = OracleHelper.NewOracleParameter(":FACTORYID", dr["FACTORYID"], OracleType.VarChar);
            insertPara[11] = OracleHelper.NewOracleParameter(":WORKFLOWREVISION", dr["WORKFLOWREVISION"], OracleType.VarChar);
            insertPara[12] = OracleHelper.NewOracleParameter(":PROCESS_NO", dr["PROCESS_NO"], OracleType.VarChar);
            insertPara[13] = OracleHelper.NewOracleParameter(":DDH", dr["DDH"], OracleType.VarChar);
            insertPara[14] = OracleHelper.NewOracleParameter(":WORKFLOWNUM", dr["WORKFLOWNUM"], OracleType.VarChar);
            // insertPara[15] = OracleHelper.NewOracleParameter(":PARTSNAME", dr["PRODUCTDESCRIPTION"], OracleType.VarChar); updateWangjh 注释
            string sql = LogHelp.TranferSql(insertSql, insertPara);
            int i = OracleHelper.ExecuteSql(insertSql, insertPara);
            if (i > 0)
                return true;
            else
                return false;
        }

        /// <summary>
        /// 插入派工信息到数据结转表
        /// </summary>
        void InsertZDSCTableSendDispatch()
        {
            DataTable dt = GetDispatchInfoToZDSC();
            if (dt.Rows.Count == 0)
                return;
            foreach (DataRow row in dt.Rows)
            {
                InsertZDSCTableSendDispatchOfRow(row);
            }
        }
        #endregion

        /// <summary>
        /// 给字典赋值(作动筒)
        /// </summary>
        /// <param name="strList"></param>
        /// <param name="dr"></param>
        void AddZDSCDctionary(ref Dictionary<string, string> strList, DataRow dr)
        {
            strList.Add("MESNO", dr["TASKNO"].ToString());//MES派工单号
            strList.Add("PartSerialNO", dr["PARTNO"].ToString());//零件号
            strList.Add("ProductName", dr["Productdescription"].ToString());//零件名称  update:Wangjh 20180713  PartSerialNO->ProductName PARTSNAME->Productdescription 
            strList.Add("FlowNO", dr["WORKFLOWNUM"].ToString());//流程编号
            strList.Add("FlowName", dr["PROCESS_NO"].ToString());//流程名称
            strList.Add("BatchPlanNum", dr["COUNT"].ToString());//批次计划数量
            strList.Add("BatchNO", dr["BATCHNO"].ToString());//批次号
            strList.Add("PlanStartDate", dr["STARTTIME"].ToString());//计划开始时间
            strList.Add("PlannedCompletionDate", dr["ENDTIME"].ToString());//计划完成时间

        }


        /// <summary>
        /// 创建试车任务信息xml字符串
        /// </summary>
        /// <param name="strList"></param>
        /// <returns></returns>
        private string CreateZDSCXML(Dictionary<string, string> strList)
        {

            XmlDocument doc = new XmlDocument();
            doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", ""));
            XmlNode ReqNode = doc.CreateElement("ReqMsg");
            XmlNode headerNode = doc.CreateElement("header");
            XmlNode senderNode = doc.CreateElement("sendSysName");
            senderNode.InnerText = "APP_MES";
            XmlNode rcvNode = doc.CreateElement("rcvSysName");
            rcvNode.InnerText = "APP_ZDSC";
            XmlNode extNode = doc.CreateElement("extConfig");
            extNode.AppendChild(doc.CreateElement("isReTry"));
            extNode.LastChild.InnerText = "false";

            headerNode.AppendChild(senderNode);
            headerNode.AppendChild(rcvNode);
            headerNode.AppendChild(extNode);
            ReqNode.AppendChild(headerNode);
            XmlNode documentNode = doc.CreateElement("document");

            string strData = "";

            strData += "<JobNode>";



            foreach (KeyValuePair<string, string> _key in strList)
            {
                strData += string.Format("<{0}>{1}</{0}>", _key.Key, _key.Value);
            }
            strData += "</JobNode>";

            documentNode.AppendChild(doc.CreateCDataSection(strData));
            ReqNode.AppendChild(documentNode);
            doc.AppendChild(ReqNode);
            return doc.InnerXml;
        }

        /// <summary>
        /// 获取待推送的派工记录
        /// </summary>
        /// <returns></returns>
        DataTable GetZDSCWaitDispatchInfo(string factoryid)
        {
            string strSql = @"SELECT * FROM mes_senddispatch_table t WHERE t.isintegration=0 and t.factoryid='" + factoryid + "'";
            return OracleHelper.Query(strSql).Tables[0];
        }
        #endregion



        /// <summary>
        /// 根据分厂代码获取分厂ID add YangJiang 20180702
        /// </summary>
        /// <param name="FactoryCode"></param>
        /// <returns></returns>
        private string GetFactoryIDByFactoryCode(string FactoryCode)
        {
            string strSQL = @"SELECT f.factoryid,f.factoryname FROM factory  f
                                LEFT JOIN Userattribute ua ON ua.parentid=f.factoryid
                                WHERE ua.userattributename='分厂代码'AND ua.attributevalue='" + FactoryCode + "'";
            DataTable dt = OracleHelper.Query(strSQL).Tables[0];
            if (dt.Rows.Count > 0)
            {
                return Convert.ToString(dt.Rows[0]["factoryid"]);
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// 获取ERP反馈XML
        /// </summary>
        /// <param name="strXML"></param>
        /// <returns></returns>
        private bool GetRcvXML(string strXML)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(strXML);
            string isSuccess = doc.SelectSingleNode("RespMsg/header/isSuccess").InnerText;
            string meaasge = doc.SelectSingleNode("RespMsg/header/message").InnerText;

            if (isSuccess.ToLower() == "true" || meaasge.ToLower() == "S")
                return true;
            else
            {
                LogHelp.WriteLog(meaasge);
                return false;
            }
        }

        /// <summary>
        /// 更新报废单信息转接标记
        /// </summary>
        /// <param name="ContainerStepScrapInfoID"></param>
        /// <param name="IsIntegration"></param>
        /// <returns></returns>
        private bool UpdateDispatchTable(string ContainerStepScrapInfoID)
        {
            string strSql = @"UPDATE mes_senddispatch_table SET ISINTEGRATION = '1'";

            strSql += " WHERE taskno = :v_recordid";
            OracleParameter[] insertParam = new OracleParameter[1];

            insertParam[0] = new OracleParameter();
            insertParam[0].ParameterName = ":v_recordid";
            insertParam[0].OracleType = OracleType.VarChar;
            insertParam[0].Direction = ParameterDirection.Input;
            insertParam[0].Value = ContainerStepScrapInfoID;

            int i = OracleHelper.ExecuteSql(strSql, insertParam);
            if (i > 0)
                return true;
            else
                return false;
        }
    }
}
